package com.kate.mall.product.service.impl;

import com.kate.mall.common.utils.RedisUtils;
import com.kate.mall.product.entity.GoodsEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kate.mall.common.utils.PageUtils;
import com.kate.mall.common.utils.Query;

import com.kate.mall.product.dao.GoodsSpecificationDao;
import com.kate.mall.product.entity.GoodsSpecificationEntity;
import com.kate.mall.product.service.GoodsSpecificationService;

import javax.annotation.Resource;


@Slf4j
@Service("goodsSpecificationService")
public class GoodsSpecificationServiceImpl extends ServiceImpl<GoodsSpecificationDao, GoodsSpecificationEntity> implements GoodsSpecificationService {

    @Resource
    private RedisUtils redisUtils;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<GoodsSpecificationEntity> page = this.page(
                new Query<GoodsSpecificationEntity>().getPage(params),
                generatorWrapper(params)
        );

        return new PageUtils(page);
    }

    @Override
    public Boolean updateRelatedCache(GoodsSpecificationEntity goodsSpecificationEntity) {
        //1.删除缓存
        redisUtils.delete("goods-service:spec:"+goodsSpecificationEntity.getId());
        redisUtils.batchDel("*spec");

        //2.更新数据库
//        try {
//            Thread.sleep(2*60*1000);//2分钟
//        } catch (InterruptedException interruptedException) {
//            interruptedException.printStackTrace();
//        }
        boolean result = this.updateById(goodsSpecificationEntity);
        if(result){
            log.info("=========关联 缓存的更新数据库成功 =======");
        }
        return result;
    }

    @Override
    public GoodsSpecificationEntity refreshCache(Integer specificationId) {
        //1.查询数据库
        GoodsSpecificationEntity specificationEntity = this.getById(specificationId);
        //2.更新缓存
        if(specificationEntity!=null){
            log.info("=========刷新缓存成功 =======");
            redisUtils.set("goods-service:spec:" +specificationId,specificationEntity);
            return specificationEntity;
        }
        return null;
    }

    private  QueryWrapper<GoodsSpecificationEntity> generatorWrapper(Map<String, Object> params){
        QueryWrapper<GoodsSpecificationEntity> queryWrapper = new QueryWrapper<>();
        if(params.containsKey("goods_id")){
            queryWrapper.lambda().eq(GoodsSpecificationEntity::getGoodsId,Integer.parseInt(String.valueOf(params.get("goods_id"))));
        }

        //TODO 要不要写逻辑删除条件？？？
        return queryWrapper;
    }



}